<?php
namespace Home\Model;
use Think\Model;
class ImagesModel extends Model 
{
	protected $insertFields = array('id','act_id');
	protected $updateFields = array('id','id','act_id');
	protected $_validate = array(
		array('act_id', 'require', '活动的id不能为空！', 1, 'regex', 3),
		array('act_id', 'number', '活动的id必须是一个整数！', 1, 'regex', 3),
	);
	public function search($pageSize = 20)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		if($act_id = I('get.act_id'))
			$where['act_id'] = array('eq', $act_id);
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->alias('a')->where($where)->group('a.id')->limit($page->firstRow.','.$page->listRows)->select();
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
		if(isset($_FILES['image']) && $_FILES['image']['error'] == 0)
		{
			$ret = uploadOne('image', 'Home', array(
				array(350, 350, 2),
				array(150, 150, 2),
				array(50, 50, 2),
			));
			if($ret['ok'] == 1)
			{
				$data['image'] = $ret['images'][0];
				$data['big_image'] = $ret['images'][1];
				$data['mid_image'] = $ret['images'][2];
				$data['sm_image'] = $ret['images'][3];
			}
			else 
			{
				$this->error = $ret['error'];
				return FALSE;
			}
		}
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
		if(isset($_FILES['image']) && $_FILES['image']['error'] == 0)
		{
			$ret = uploadOne('image', 'Home', array(
				array(350, 350, 2),
				array(150, 150, 2),
				array(50, 50, 2),
			));
			if($ret['ok'] == 1)
			{
				$data['image'] = $ret['images'][0];
				$data['big_image'] = $ret['images'][1];
				$data['mid_image'] = $ret['images'][2];
				$data['sm_image'] = $ret['images'][3];
			}
			else 
			{
				$this->error = $ret['error'];
				return FALSE;
			}
			deleteImage(array(
				I('post.old_image'),
				I('post.old_big_image'),
				I('post.old_mid_image'),
				I('post.old_sm_image'),
	
			));
		}
	}
	// 删除前
	protected function _before_delete($option)
	{
		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
		$images = $this->field('image,big_image,mid_image,sm_image')->find($option['where']['id']);
		deleteImage($images);
	}
	/************************************ 其他方法 ********************************************/
}